package com.jin.spring_boot_learn.concurrent.locks.reentranceLock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用syn锁定的话如果遇到异常，jvm会自动释放锁，但是lock必须手动释放锁，因此经常在finally中进行锁的释放
 * 使用ReentrantLock还可以调用lockInterruptibly方法，可以对线程interrupt方法做出响应，
 * 在一个线程等待锁的过程中，可以被打断
 */
public class ReentrantLockTest02 {
    private static final ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {


        Thread t1 = new Thread(() -> {
            try {
                lock.lock();
                System.out.println("t1 start");
                TimeUnit.SECONDS.sleep(Integer.MAX_VALUE); // sleep 让渡 cup 但是不会释放锁
                System.out.println("t1 end");
            } catch (InterruptedException e) {
                System.out.println(" t1 interupt  end");
            } finally {
                lock.unlock();
            }
        });

        Thread t2 = new Thread(() -> {
            System.out.println("t2 start");
            try {
                lock.lockInterruptibly(); //  可以对interrupt()方法做出响应
            } catch (InterruptedException e) {
                System.out.println("t2 被打断了");
            }finally {
                if(lock.isHeldByCurrentThread()){
                    lock.unlock();
                }
            }
            System.out.println("t2 end");
        });

        t1.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        t2.start();

        try {
            Thread.sleep(5*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        t2.interrupt();
    }
}
